/**
 * Copyright (C) 2017-2030 http://www.ejianmedia.com/ 冯兵兵 <cnrainbing@163.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.fastadmin.common.jedis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

/**
 *
 * @Author: YangKun
 * @Date: 19-8-2
 */
public class JedisUtils {
    private static Logger logger = LoggerFactory.getLogger(JedisUtils.class);

    private static final String OK_CODE = "OK";
    private static final String OK_MULTI_CODE = "+OK";


    /**
     * 判断 返回值是否ok.
     */
    public static boolean isStatusOk(String status) {
        return (status != null) && (OK_CODE.equals(status) || OK_MULTI_CODE.equals(status));
    }

    /**
     * Return jedis connection to the pool, call different return methods depends on the conectionBroken status.
     */
	public static void closeResource(Jedis jedis) {
        try {
            jedis.close();
        } catch (Exception e) {
            logger.error("return back jedis failed, will fore close the jedis.", e);
            destroyJedis(jedis);
        }
    }

    /**
     * 在Pool以外强行销毁Jedis.
     */
    public static void destroyJedis(Jedis jedis) {
        if ((jedis != null) && jedis.isConnected()) {
            try {
                try {
                    jedis.quit();
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("在Pool以外强行销毁Jedis quit error:{}", e.getMessage());
                }
                jedis.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("在Pool以外强行销毁Jedis disconnect error:{}", e.getMessage());
            }
        }
    }
}
